package com.apkicon.parser;

import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;

/**
 * Android原生XML图标解析器
 * 按照PackageManager的方式处理Vector Drawable
 */
public class AndroidXmlIconParser {
    
    /**
     * 检查是否为Vector Drawable
     */
    public static boolean isVectorDrawable(byte[] xmlData) {
        if (xmlData == null || xmlData.length < 10) {
            return false;
        }
        
        // 检查XML头部
        String xmlContent = new String(xmlData, 0, Math.min(100, xmlData.length));
        return xmlContent.contains("vector") || xmlContent.contains("VectorDrawable");
    }
    
    /**
     * 检查是否为Adaptive Icon
     */
    public static boolean isAdaptiveIcon(byte[] xmlData) {
        if (xmlData == null || xmlData.length < 10) {
            return false;
        }
        
        // 检查XML头部
        String xmlContent = new String(xmlData, 0, Math.min(100, xmlData.length));
        return xmlContent.contains("adaptive-icon") || xmlContent.contains("AdaptiveIcon");
    }
    
    /**
     * 从APK中读取XML文件内容
     */
    public static byte[] readXmlFromApk(ZipFile apkFile, String xmlPath) {
        try {
            ZipEntry entry = apkFile.getEntry(xmlPath);
            if (entry == null) {
                return null;
            }
            
            try (InputStream is = apkFile.getInputStream(entry);
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }
                
                return baos.toByteArray();
            }
        } catch (Exception e) {
            System.err.println("读取XML文件失败: " + xmlPath + " - " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 解析XML图标信息
     */
    public static XmlIconInfo parseXmlIcon(byte[] xmlData) {
        if (xmlData == null) {
            return null;
        }
        
        try {
            String xmlContent = new String(xmlData, "UTF-8");
            
            if (isVectorDrawable(xmlData)) {
                return parseVectorDrawable(xmlContent);
            } else if (isAdaptiveIcon(xmlData)) {
                return parseAdaptiveIcon(xmlContent);
            } else {
                System.out.println("⚠️ 未知的XML图标格式");
                return null;
            }
        } catch (Exception e) {
            System.err.println("解析XML图标失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 解析Vector Drawable
     */
    private static XmlIconInfo parseVectorDrawable(String xmlContent) {
        try {
            // 提取基本属性
            int width = extractIntAttribute(xmlContent, "android:width", 24);
            int height = extractIntAttribute(xmlContent, "android:height", 24);
            
            // 检查是否有viewport
            int viewportWidth = extractIntAttribute(xmlContent, "android:viewportWidth", width);
            int viewportHeight = extractIntAttribute(xmlContent, "android:viewportHeight", height);
            
            System.out.println("🔍 Vector Drawable: " + width + "x" + height + 
                             " (viewport: " + viewportWidth + "x" + viewportHeight + ")");
            
            return new XmlIconInfo("vector", width, height, viewportWidth, viewportHeight, xmlContent);
        } catch (Exception e) {
            System.err.println("解析Vector Drawable失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 解析Adaptive Icon
     */
    private static XmlIconInfo parseAdaptiveIcon(String xmlContent) {
        try {
            // Adaptive Icon通常是108dp x 108dp
            int width = extractIntAttribute(xmlContent, "android:width", 108);
            int height = extractIntAttribute(xmlContent, "android:height", 108);
            
            System.out.println("🔍 Adaptive Icon: " + width + "x" + height);
            
            return new XmlIconInfo("adaptive", width, height, width, height, xmlContent);
        } catch (Exception e) {
            System.err.println("解析Adaptive Icon失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 从XML内容中提取整数属性
     */
    private static int extractIntAttribute(String xmlContent, String attributeName, int defaultValue) {
        try {
            String pattern = attributeName + "=\"";
            int startIndex = xmlContent.indexOf(pattern);
            if (startIndex == -1) {
                return defaultValue;
            }
            
            startIndex += pattern.length();
            int endIndex = xmlContent.indexOf("\"", startIndex);
            if (endIndex == -1) {
                return defaultValue;
            }
            
            String value = xmlContent.substring(startIndex, endIndex);
            
            // 处理dp单位
            if (value.endsWith("dp")) {
                value = value.substring(0, value.length() - 2);
            }
            
            return Integer.parseInt(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }
    
    /**
     * XML图标信息
     */
    public static class XmlIconInfo {
        private final String type;
        private final int width;
        private final int height;
        private final int viewportWidth;
        private final int viewportHeight;
        private final String xmlContent;
        
        public XmlIconInfo(String type, int width, int height, int viewportWidth, int viewportHeight, String xmlContent) {
            this.type = type;
            this.width = width;
            this.height = height;
            this.viewportWidth = viewportWidth;
            this.viewportHeight = viewportHeight;
            this.xmlContent = xmlContent;
        }
        
        public String getType() { return type; }
        public int getWidth() { return width; }
        public int getHeight() { return height; }
        public int getViewportWidth() { return viewportWidth; }
        public int getViewportHeight() { return viewportHeight; }
        public String getXmlContent() { return xmlContent; }
        
        @Override
        public String toString() {
            return String.format("XmlIconInfo{type='%s', size=%dx%d, viewport=%dx%d}", 
                               type, width, height, viewportWidth, viewportHeight);
        }
    }
}
